package com.xu.modules.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xu.common.enums.StationNumTypeEnum;
import com.xu.modules.entity.VisitorEntity;
import com.xu.modules.mapper.VisitorMapper;
import com.xu.modules.service.StationService;
import com.xu.modules.service.VisitorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 访客表 服务实现类
 * </p>
 *
 * @author xu
 * @since 2022-07-28
 */
@Service
@RequiredArgsConstructor
public class VisitorServiceImpl extends ServiceImpl<VisitorMapper, VisitorEntity> implements VisitorService {
    private final VisitorMapper visitorMapper;
    private final StationService stationService;

    @Override
    public void add(String ip) {
        if(StrUtil.isBlank(ip)){
            return;
        }
        // 统计IP
        Long countByIp = countByIp(ip);
        // 如果等于0 说明是新访客
        if(countByIp == 0){
            VisitorEntity.VisitorEntityBuilder visitorEntityBuilder = VisitorEntity.builder().visitorIp(ip);
            visitorMapper.insert(visitorEntityBuilder.build());
            stationService.changeStationNum(StationNumTypeEnum.VISITOR);
        }
    }

    @Override
    public Long countByIp(String ip) {
        LambdaQueryWrapper<VisitorEntity> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(ip),VisitorEntity::getVisitorIp,ip);
        return visitorMapper.selectCount(lqw);
    }
}
